package job.manager.icefaces.validator;

import java.util.StringTokenizer;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;



/**
 *  Validator for checking if the email is correct.
 * 
 */
public class EmailValidator implements Validator {

    //validate function that is called.
    
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if( value instanceof String){

            String v = (String)value;
            if( !this.validateEmail(v) ){
                FacesMessage msg = new FacesMessage();
                msg.setDetail("Email felaktig");
                msg.setSummary("Email felaktig");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(msg);
            }
        }
    }

     private boolean validateEmail(String email) {
        // Input the string for validation
        // String email = "xyz@.com";
        // Set the email pattern string
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

        // Match the given string with the pattern
        Matcher m = p.matcher(email);

        // check whether match is found
        boolean matchFound = m.matches();

        StringTokenizer st = new StringTokenizer(email, ".");
        String lastToken = null;
        while (st.hasMoreTokens()) {
            lastToken = st.nextToken();
        }

        if (matchFound && lastToken.length() >= 2 && email.length() - 1 != lastToken.length()) {
            //valid email
            return true;
        } else {
            return false;
        }
    }

}
